<template>
  <!-- 合同变更 -->
  <div class="contractInfo box">
    <el-divider content-position="left">合同变更</el-divider>
    <!-- <div class="formBox"> -->
    <el-form
      :model="contractForm"
      :rules="rules"
      ref="addForm"
      label-width="auto"
      label-position="right"
      style="width: 100%"
    >
      <!-- <el-form-item label="合同编号" prop="num" required style="width: 100%">
          <p>{{ contractForm.num }}</p>
        </el-form-item> -->
      <el-card
        shadow="hover"
        header="基本信息"
        class="item-background formBox"
        style="width: 100%"
      >
        <el-form-item label="关联报价" prop="quotesData" class="formRow">
          <sc-table-select
            v-model="contractForm.quotesData"
            :apiObj="apiObj"
            style="width: 100%"
            :table-width="700"
            clearable
            collapse-tags
            collapse-tags-tooltip
            :props="quotesProps"
            @change="quotesChange"
            disabled
          >
            <template #header="{ form, submit }">
              <el-form :inline="true" :model="form">
                <el-form-item>
                  <el-input
                    v-model="form.search"
                    placeholder="报价名称"
                    clearable
                  ></el-input>
                </el-form-item>
                <el-button type="primary" @click="submit">查询</el-button>
              </el-form>
              <!-- <el-alert title="自定义FORM插糟 传递了form对象和提交方法" type="info" /> -->
            </template>
            <el-table-column
              label="报价名称"
              prop="quotesName"
              min-width="150"
            ></el-table-column>
            <el-table-column
              label="客户名称"
              prop="customerName"
              min-width="150"
            ></el-table-column>
            <el-table-column
              label="报价总额"
              prop="price"
              width="100"
            ></el-table-column>
            <el-table-column
              label="报价日期"
              prop="createTime"
              width="200"
            ></el-table-column>
          </sc-table-select>
          <el-button type="primary" @click="toQuoteDetail">详情</el-button>
        </el-form-item>

        <el-form-item label="合同名称" prop="name" style="100%">
          <el-input
            v-model="contractForm.name"
            placeholder="请输入合同名称"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="合同简称">
          <el-input
            v-model="contractForm.simpleName"
            placeholder="请输入合同简称"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="甲方" prop="lessor">
          <el-input
            v-model="contractForm.lessor"
            placeholder="请输入甲方名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="甲方电话" prop="">
          <el-input
            v-model="contractForm.lessorPhone"
            placeholder="请输入甲方电话"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="乙方" prop="partyBName">
          <el-input
            v-model="contractForm.partyBName"
            placeholder="请输入乙方名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="合同类型" prop="type">
          <el-select
            v-model="contractForm.type"
            placeholder="请选择合同类型"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in contractType"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="合同总额" prop="money">
          <el-input
            v-model="contractForm.money"
            placeholder="请输入合同金额"
            clearable
            disabled
          >
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="条款" class="formRow">
          <!-- <el-input
            v-model="contractForm.lessorArticle"
            clearable
            type="textarea"
            rows="6"
            placeholder="请输入合同条款"
          ></el-input> -->
          <el-select
            v-model="contractForm.articleList.id"
            placeholder="请选择合同条款"
            style="width: 100%"
            clearable
            @change="getClauseById"
          >
            <el-option
              v-for="item in articleList"
              :key="item.id"
              :label="item.articleTitle"
              :value="item.id"
            />
          </el-select>
          <el-button type="primary" @click="showClauseDetail(articleItem)"
            >编辑</el-button
          >
        </el-form-item>
        <el-form-item label="签订时间" prop="orderTime">
          <el-date-picker
            v-model="contractForm.orderTime"
            type="date"
            placeholder="请选择签订时间"
            size="default"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="签订地点">
          <el-input
            v-model="contractForm.orderAddress"
            clearable
            placeholder="请输入签订地点"
          ></el-input>
        </el-form-item>
        <el-form-item label="交货时间">
          <el-date-picker
            v-model="contractForm.deliveryTime"
            type="date"
            placeholder="请选择交货时间"
            size="default"
            style="width: 100%"
            value-format="YYYY-MM-DD"
            disabled
          />
        </el-form-item>
        <el-form-item label="是否是建模合同">
          <el-radio-group v-model="contractForm.modeling">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否含税">
          <el-radio-group v-model="contractForm.isIncludingTax">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="税率" v-if="contractForm.isIncludingTax === 1">
          <el-select
            v-model="contractForm.taxRate"
            placeholder="请选择税率"
            style="width: 100%"
            clearable
          >
            <el-option label="6%" value="1" />
            <el-option label="13%" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark" style="width: 100%">
          <el-input
            v-model="contractForm.remark"
            clearable
            type="textarea"
            rows="6"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
        <el-form-item label="附件" style="width: 100%">
          <sc-upload-file
            v-model="contractForm.otherFiles"
            :limit="10"
            :multiple="false"
            tip="最多上传10个文件,单个文件不要超过20M"
          >
            <el-button type="primary" plain icon="el-icon-upload"
              >上传附件</el-button
            >
          </sc-upload-file>
        </el-form-item>
        <el-form-item label="变更版本" prop="changeVersion">
          <el-input
            v-model="contractForm.changeVersion"
            placeholder="请输入变更版本"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="变更理由" prop="changeReason" style="width: 100%">
          <el-input
            v-model="contractForm.changeReason"
            clearable
            type="textarea"
            rows="3"
            placeholder="请输入变更理由"
          ></el-input>
        </el-form-item>
      </el-card>
      <el-divider />
      <el-card
        shadow="hover"
        header="产品信息"
        class="item-background formBox"
        style="width: 100%"
      >
        <el-form-item
          label="产品列表"
          prop="contractProductsList"
          style="width: 100%"
        >
          <sc-form-table
            ref="table"
            v-model="contractForm.contractProductsList"
            :addTemplate="productsTemplate"
            placeholder="暂无数据"
          >
            <el-table-column label="产品名称" min-width="150">
              <template #default="scope">
                <sc-table-select
                  v-model="scope.row.productsData"
                  :apiObj="productsApiObj"
                  table-width="100%"
                  clearable
                  collapse-tags
                  collapse-tags-tooltip
                  :props="productsProps"
                  @change="productChange(scope.row)"
                  style="width: 100%"
                >
                  <template #header="{ form, submit }">
                    <el-form :inline="true" :model="form">
                      <el-form-item>
                        <el-input
                          v-model="form.search"
                          placeholder="产品名称"
                        ></el-input>
                      </el-form-item>
                      <el-button type="primary" @click="submit">查询</el-button>
                    </el-form>
                  </template>
                  <el-table-column
                    label="产品名称"
                    prop="name"
                    min-width="100"
                  ></el-table-column>
                  <el-table-column
                    label="规格型号"
                    prop="specification"
                    min-width="100"
                  ></el-table-column>
                  <el-table-column
                    label="产品单价"
                    prop="onePrice"
                    width="100"
                  ></el-table-column>
                  <el-table-column
                    label="产品单位"
                    prop="unitName"
                    width="100"
                  ></el-table-column>
                </sc-table-select>
              </template>
            </el-table-column>
            <el-table-column
              label="规格型号"
              prop="specification"
              min-width="150"
            >
            </el-table-column>
            <el-table-column prop="onePrice" label="单价" width="250">
              <template #default="scope">
                <el-input-number
                  :precision="2"
                  v-model.number="scope.row.onePrice"
                  placeholder="请输入单价"
                  @change="changePrice(scope.row)"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="num" label="数量" width="250">
              <template #default="scope">
                <el-input-number
                  :precision="0"
                  v-model.number="scope.row.num"
                  placeholder="请输入数量"
                  @change="changePrice(scope.row)"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="总金额" width="200">
              <template #default="scope">
                <el-input v-model="scope.row.price" :disabled="true"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="unitName" label="单位" width="180">
              <template #default="scope">
                {{ scope.row.unitName }}
              </template>
            </el-table-column>
          </sc-form-table>
        </el-form-item>
      </el-card>
      <el-divider />
      <el-card
        shadow="hover"
        header="生产信息"
        class="item-background formBox"
        style="width: 100%"
      >
        <el-form-item label="生产负责人" prop="productionPerson">
          <el-select
            v-model="contractForm.productionPerson"
            placeholder="请选择负责人"
            style="width: 100%"
            clearable
            filterable
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生产截止时间" prop="endTime">
          <el-date-picker
            v-model="contractForm.endTime"
            type="date"
            placeholder="请选择生产截止时间"
            size="default"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-card>
    </el-form>
    <el-divider />
    <el-card
      shadow="hover"
      header="审核信息"
      class="item-background formBox"
      style="width: 100%"
    >
      <check-form-item
        ref="checkFormItem"
        @setCheckConfig="setCheckConfig"
        :field="this.contractForm"
        :checkType="checkType"
        style="width: 100%"
      ></check-form-item>
      <div class="button">
        <el-button type="primary" @click="save" :loading="isSaveing"
          >保 存</el-button
        >
        <el-button @click="cencel">取 消</el-button>
      </div>
    </el-card>
    <!-- 审核流程项 -->
  </div>
  <!-- </div> -->
  <clause-dialog ref="clauseDialog" @saveClauseDetail="saveClauseDetail">
  </clause-dialog>
</template>
<script>
import { queryTypeByDic } from "@/utils/getData"
import checkFormItem from "@/components/checkProcess/checkFormItem.vue"
import clauseDialog from "../components/clauseDialog.vue"
import { ElCard } from "element-plus"
export default {
  name: "",
  data () {
    return {
      checkType: 27, //工作流的类型
      isSaveing: false,
      selectQuotesLoading: false,
      //表单数据
      contractForm: {
        adminId: "", //跟进人id --登录时id
        departmentId: "",
        contractId: '',
        //customerId: '',
        num: "", //合同编号
        name: "", //合同名称
        simpleName: "", //合同简称
        lessor: "", //甲方
        lessorPhone: "", //甲方电话
        // secondPhone: '',//客户电话
        partyBName: "", //乙方名称
        type: 1, //合同类型
        money: "", //金额
        orderTime: this.$TOOL.dateFormat(new Date(), "yyyy-MM-dd"), //签订时间
        orderAddress: "", //签订地点
        deliveryTime: "", //交货时间
        // lessorArticle: '',//条款
        articleList: {}, //条款-*
        remark: "", //备注
        otherFiles: [], //附件
        workflowJsonList: [],
        // settlement: '',//结算方式
        quotesData: {}, //选择器数据
        productionPerson: "", //生产负责人
        endTime: "", // 生产截止时间
        exempt: "", //是否免审
        modeling: 0,//是否是建模合同
        isIncludingTax: 0, //	是否含税:0不含税，1含税
        taxRate: "", //税率
        changeReason: '',//变更理由
        changeVersion: '',//变更版本
        changeContractProducts: ''
      },
      settlementOptions: [
        { name: "现结", value: 1 },
        { name: "月结", value: 2 },
      ],
      apiObj: this.$API.contract.quoteManagement.getStatusQuotes,
      quotesProps: {
        label: "quotesName",
        value: "id",
        keyword: "keyword",
      },
      //产品模版
      productsTemplate: {
        name: '',
        specification: '',
        num: '',
        onePrice: '',
        price: '',
        productsId: '',
        productsData: {},
      },
      productsProps: {
        label: 'name',
        value: 'id',
      },
      productsApiObj: this.$API.vendorProducts.selectVendorProductsList,
      articleList: [], //合同条款列表
      articleItem: [], //条款项
      contractType: [], //合同类型
      customerList: [], //客户列表
      userList: [], //用户列表
      settlementDisabled: false,
      checkConfigData: { workflowJsonList: [], exempt: 0 },//审核流数据
      //验证规则
      rules: {
        name: [{ required: true, message: "请输入合同名称" }],
        simpleName: [{ required: true, message: "请输入合同简称" }],
        lessor: [{ required: true, message: "请输入甲方" }],
        lessorPhone: [{ required: true, message: "请输入甲方电话" }],
        customerId: [{ required: true, message: "请选择客户", trigger: "change" }],
        partyBName: [{ required: true, message: "请输入乙方名称" }],
        type: [{ required: true, message: "请选择合同类型", trigger: "change" }],
        money: [{ required: true, message: "请输入合同金额" }],
        orderTime: [
          { type: "date", required: true, message: "请选择签订时间", trigger: "change" },
        ],
        quotesData: [{ required: true, message: "请选择报价", trigger: "change" }],
        paymentMethod: [{ required: true, message: "请选择付款方式", trigger: "change" }],
        prepaymentMoney: [{ required: true, message: "请输入预付款金额" }],
        isIncludingTax: [
          { required: true, message: "请勾选是否含税", trigger: "change" },
        ],
        changeVersion: [
          { required: true, message: "请输入变更版本" }
        ]
      },
    }
  },
  components: {
    checkFormItem,
    clauseDialog,
    ElCard,
  },
  mounted () {
    this.getContractConfig()
    this.getDefaultClause()
    this.getType()
    this.getArticleList()
    this.getUserList()
    this.getContractById()

  },
  methods: {
    // 跳转到报价详情
    toQuoteDetail () {
      if (!this.contractForm.quotesData.id) {
        this.$message.error("请选择报价")
        return
      }
      this.$router.push({
        path: "/customer/quoteManagement/quoteDetail",
        query: {
          id: this.contractForm.quotesData.id,
        },
      })
    },
    productChange (row) {
      console.log(row)
      row.name = row.productsData.name
      row.specification = row.productsData.specification
      row.onePrice = row.productsData.onePrice
      row.unitName = row.productsData.unitName
      row.unit = row.productsData.unit
      row.productsId = row.productsData.id
    },
    // 价格改变
    changePrice (row) {
      row.price = (row.onePrice * row.num).toFixed(2)
      this.contractForm.money = 0
      this.contractForm.contractProductsList.forEach(element => {
        this.contractForm.money = +this.contractForm.money + (+element.price)
      })
      console.log(this.contractForm)
    },

    // 获取合同默认配置
    async getContractConfig () {
      let { data } = await this.$API.contract.contractConfig.getConfigDetail.post({
        id: 1,
      })
      this.contractForm.partyBName = data.partyBName
      this.contractForm.productionPerson = data.produceAdminId
      this.contractForm.orderAddress = data.signedAddress
    },

    // 获取合同类型
    async getType () {
      this.contractType = await queryTypeByDic("contractType")
    },
    // 选择器值变化时
    quotesChange (row) {
      this.contractForm.name = "【" + row.customerName + "】的合同"
      this.contractForm.money = row.price
      this.contractForm.lessor = row.customerName
      let date = new Date()
      let time = row.deliveryTime ? +row.deliveryTime : 0
      date.setDate(date.getDate() + time)
      this.contractForm.deliveryTime = this.$TOOL.dateFormat(date, "yyyy-MM-dd")
      // this.contractForm.settlement = row.settlement
      // this.contractForm.settlement == 1 ? this.settlementDisabled = true : this.settlementDisabled = false
    },
    // 获取合同条款列表
    async getArticleList () {
      let { data } = await this.$API.contract.contractClause.getClauseList.get()
      this.articleList = data
    },

    // 获取所有用户列表
    async getUserList (val) {
      let data = {
        limit: 1000,
        page: 1,
        search: val,
      }
      let res = await this.$API.user.getUserList.get(data)
      this.userList = res.data
    },

    // 搜索用户
    queryUser (val) {
      this.getUserList(val)
    },

    // 审批流配置
    setCheckConfig (list, exempt) {
      // this.contractForm.workflowJsonList = list
      // this.contractForm.exempt = exempt
      this.checkConfigData.workflowJsonList = list
      this.checkConfigData.exempt = exempt
    },

    // 根据id 获取合同详情
    async getContractById () {
      let { data } = await this.$API.contract.getContractById.post({
        id: this.$route.query.id,
      })
      this.contractForm = data
      this.contractForm.contractProductsList.forEach(item => {
        item.productsData = { ...item }
      })
      this.contractForm.contractId = data.id
      this.contractForm.workflowJsonList = this.checkConfigData.workflowJsonList
      this.contractForm.exempt = this.checkConfigData.exempt
      delete this.contractForm.status
      delete this.contractForm.id
      delete this.contractForm.updateTime
      delete this.contractForm.createTime
      if (!this.contractForm.otherFiles) this.contractForm.otherFiles = []
      this.contractForm.otherFiles.forEach((item) => {
        item.name = item.fileName
      })
      if (this.contractForm.articleList) {
        this.contractForm.articleList.articleText = this.contractForm.lessorArticle
        this.contractForm.articleList.articleTitle = this.contractForm.lessorArticleTitle
        this.articleItem = this.contractForm.articleList
      } else {
        this.contractForm.articleList = {}
      }

    },

    // 获取默认条款
    async getDefaultClause () {
      let { data } = await this.$API.contract.contractClause.getDefaultClause.get()
      this.contractForm.articleList = data
      this.articleItem = data
    },


    // 根据id获取条款详情
    async getClauseById (id) {
      let { data } = await this.$API.contract.contractClause.getClauseById.post({
        articleId: this.contractForm.articleList.id,
      })
      this.articleItem = data
    },

    // 查看条款详情
    showClauseDetail (data) {
      console.log(this.contractForm)
      // let detail = {}
      // if (this.$route.query.mode == 'edit') {
      //   // detail = {
      //   //   articleText: this.contractForm.lessorArticle,
      //   //   articleTitle: this.contractForm.lessorArticleTitle,
      //   //   id: this.articleItem.id
      //   // }
      //   detail = this.contractForm.articleList
      // } else {
      //   detail = data
      // }
      this.$refs.clauseDialog.open(data)
    },

    saveClauseDetail (data) {
      // console.log(data)
      this.contractForm.articleList = { ...data }

      this.articleItem = data
    },

    // 保存合同添加
    async save () {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          this.isSaveing = true
          let userInfo = this.$TOOL.data.get("USER_INFO")
          this.contractForm.adminId = userInfo.userId
          this.contractForm.departmentId = userInfo.departmentId
          this.$route.query.quoteId
            ? (this.contractForm.quotesId = this.$route.query.quoteId)
            : (this.contractForm.quotesId = this.contractForm.quotesData.id)
          this.contractForm.changeContractProducts = JSON.stringify(this.contractForm.contractProductsList)
          let fileType = ""
          this.contractForm.otherFiles.map((item) => {
            if (item.url) {
              let arr = item.url.split(".")
              let type = arr[arr.length - 1]
              // fileType  1图片 2文件
              let imageType = "jpg/png/jpeg/svg"
              if (imageType.includes(type)) {
                fileType = 1
              } else {
                fileType = 2
              }
              item.fileType = fileType
              item.fileName = item.name
            }
          })
          let mode = this.$route.query.mode
          let res = await this.$API.contract.contractChange.addContractChange.post(this.contractForm)

          if (res.code == 200) {
            this.$message.success("操作成功")
            this.isSaveing = false
            this.closeSelectedTag(this.$route)
            this.$router.push({
              path: "/contract/changeManagement",
            })
          }
        }
      })
    },
    // 取消合同添加
    cencel () {
      this.closeSelectedTag(this.$route)
      this.$router.push({
        path: "/contract/contractManagement",
      })
    },
    //关闭tag
    closeSelectedTag (tag) {
      this.$store.commit("removeViewTags", tag)
      this.$store.commit("removeIframeList", tag)
      this.$store.commit("removeKeepLive", tag.name)
    },
  },
};
</script>
<style lang="scss" scoped>
.box {
  margin: 10px;
}
:deep(.el-card__body) {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.formBox {
  padding: 30px;
  background: #fff;

  .el-form {
    width: 100%;
  }
}
.formRow {
  :deep(.el-form-item__content) {
    flex-wrap: nowrap;
    .el-button {
      margin-left: 10px;
    }
  }
}
.button {
  margin-top: 50px;
  padding-left: 60px;
}

:deep(.el-divider__text) {
  padding: 0 10px;
  font-size: 18px;
  // font-weight: 600;
  background-color: #f6f8f9;
}

// :deep(.el-form .el-form-item) {
//   width: 80%;
// }

.title {
  margin-top: 5px;
  color: #409eff;
  cursor: pointer;

  &:hover {
    text-decoration: underline;
  }
}
</style>
